package de.slothsoft.wasbinich.android.preference;

import java.util.Locale;

import android.app.Activity;
import android.os.Build;
import android.preference.Preference;
import de.slothsoft.wasbinich.android.util.ActivityUtil;

public class LocalePreferenceChangeListener implements Preference.OnPreferenceChangeListener {

    private final Activity settingsActivity;

    public LocalePreferenceChangeListener(Activity settingsActivity) {
	this.settingsActivity = settingsActivity;
    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object value) {
	if (value != null) {
	    Locale newLocale = new Locale(value.toString());
	    if (!newLocale.equals(Locale.getDefault())) {
		Locale.setDefault(newLocale);
		reloadLocale(newLocale);
	    }
	    preference.setSummary(newLocale.getDisplayLanguage());
	}
	return true;
    }

    private void reloadLocale(Locale newLocale) {
	ActivityUtil.reloadLocale(this.settingsActivity, newLocale);
	for (Activity activity : ActivityUtil.getAllActivities()) {
	    recreateActivity(activity);
	}
	recreateActivity(this.settingsActivity);
    }

    private void recreateActivity(Activity activity) {
	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
	    activity.recreate();
	} else {
	    activity.finish();
	    activity.startActivity(activity.getIntent());
	}
    }

}
